//
//  SemTableView.m
//  Gradekeeper0.2
//
//  Created by Ben Wu on 11/18/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

//  reference: http://broadcast.oreilly.com/2009/06/tab-bars-and-navigation-bars-t.html
//  reference: http://stackoverflow.com/questions/259956/nsstring-tokenize-in-objective-c
//  reference: http://blog.ablepear.com/2009/06/nsmutablearray-and-removeobjectatindex.html
//  reference: http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html
//
//  filepath: /Users/yhw3/Library/Application Support/iPhone Simulator/User/Applications/D35688F2-4AAC-4CE0-A4E3-FAB60FB229FE/Documents/

#import "SemTableView.h"
#import "SDetailViewController.h"
#import "Gradekeeper0_2AppDelegate.h"
#import "semYear.h"
#import "fileIO.h"
#import "Profile.h"
#import <Foundation/NSObject.h>

/*
 SemTableView will provide necessary view and function for Course system.
 Clicking create button will call a function that pushes the view to Year, handled by semYear.
 Course.txt will be created upon loading of view for first time, and will be read if it already exist. A list of created year will be displayed.
 Clicking on an existing year will push the view to semester detailed view, handled by SDetailViewController.
 Deleting the year will delete the text file, delete the year from course.txt, and delete it from the table.
 */

@implementation SemTableView

//@synthesize semArray;
@synthesize sDetailViewController;
@synthesize yearController;
@synthesize profile;

- (void) setRow: (NSUInteger) inputRow{
	rowToDelete = inputRow;
} //setRow

- (NSUInteger) getRow{
	return rowToDelete;
} //getRow

//If user chooses to create a new year
//the view will change to year
- (IBAction) createPressed:(id)sender {
	if (self.yearController == nil){
		semYear * sController = [[semYear alloc] initWithNibName:@"semYear" bundle:nil];
		self.yearController = sController;
		[sController release];
	}
	
	[self.navigationController pushViewController:yearController animated:YES];
} //createPressed

//Set up alert button function
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
	//If user confirms file deletion, the file will be removed from course.txt
	//The text file will also be removed from the respective directory and from the table view
	if ([alertView.title isEqualToString:@"Delete Confirmation"]){
		if (buttonIndex == 0) {
			
			NSFileManager  *NSFm;
			
			NSFm = [NSFileManager defaultManager] ;
			
			NSString *temp = [NSString stringWithFormat:@"%@", [[self.profile semesters] objectAtIndex:rowToDelete]];
			
			
			[NSFm removeItemAtPath:[fileIO getFilePath:temp] error:NULL] ;
			
			[fileIO deleteFromFile:@"Course" :temp :@":"];
			[[self.profile semesters] removeObjectAtIndex:rowToDelete];
			[self.tableView reloadData];
		}
	} 
} //alertView

- (void)viewDidLoad {
    [super viewDidLoad];
	
	// display an Edit button in the navigation bar for this view controller
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
	
	// create a custom navigation bar button and set it to say "back"
	/*UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
	temporaryBarButtonItem.title = @"Back";
	self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
	[temporaryBarButtonItem release];*/
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	
	//Create a Course.txt if it has not been created.
	//If a Course.txt already exist, read from the file and fill the table with created year
	self.profile = [Profile sharedProfile];
	NSString *course = @"Course";
	NSString *tempsemList = nil;
	
	if ([fileIO fileExist:course]){
		tempsemList = [[NSString alloc] initWithFormat:@"%@", [fileIO readFromFile:course]];
	} else {
		[fileIO writeToFile:course : @""];
	};
	
	NSArray *tempArray = [tempsemList componentsSeparatedByString: @":"];
	NSMutableArray *semList = [[NSMutableArray alloc] initWithCapacity:1];
	
	for (int y = 1; y < [tempArray count]; y ++){
		[semList addObject: [tempArray objectAtIndex:y]];
	};
	
	
	[tempsemList release];
	
	[self.profile setSemesters:semList];
	[semList release];
	
	[self.tableView reloadData];
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
	[super setEditing:editing animated:animated];
	if(editing) {
		self.navigationItem.rightBarButtonItem.enabled = NO;
	} else {
		self.navigationItem.rightBarButtonItem.enabled = YES;
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/* the following functions applies to table view*/

//Set up table view
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.profile semesters] count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	NSUInteger row = [indexPath row];
	cell.textLabel.text = [[self.profile semesters] objectAtIndex:row];
	return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	
	//If user selects a row, the current view will change to SDetailViewController that contains the semester information
	NSInteger row = [indexPath row];
	NSString *selectedyear = [NSString stringWithFormat:@"%@", [[self.profile semesters] objectAtIndex:row]];													   

	self.sDetailViewController = [[SDetailViewController alloc] initWithNibName:@"SDetailViewController" bundle:nil semester:[[self.profile semesters] objectAtIndex:row]];
	sDetailViewController.title = selectedyear;
	
	//Profile *year = [Profile sharedProfile]; //from created function from Profile.h
	//[year setUserName:selectedyear];
	
	[self.navigationController pushViewController:sDetailViewController animated:YES];
	[sDetailViewController release];
	self.sDetailViewController = nil;
}

- (UITableViewCellAccessoryType)tableView:(UITableView *)tv accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellAccessoryDisclosureIndicator;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
	//If user chooses to delete a year, an alert box will pop up to confirm user's request
	//If user chooses yes, the file will be deleted. 
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		rowToDelete = indexPath.row;
		
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"Delete Confirmation" 
							  message:@"Are you sure you would like to delete current year? \n All information stored under the this year will be deleted." 
							  delegate:self
							  cancelButtonTitle:@"Yes" 
							  otherButtonTitles:nil]; 
		[alert addButtonWithTitle:@"No"];
		
		[alert show];
		
		[alert release];
		
		[self.tableView reloadData];
		
		
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // do nothing
    }   
}


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


- (void)dealloc {
	[yearController release];
	[sDetailViewController release];
	[profile release];
    [super dealloc];
}




@end

